/* eslint-disable react-refresh/only-export-components */
import type { FC, PropsWithChildren } from "react";
import { Navigate } from "react-router-dom";
import { memo } from "react";
import { useLocation } from "react-router";
import { useSelector } from "react-redux";
interface Props {
  intoPermission: boolean;
  code: string;
}
const Permission: FC<PropsWithChildren<Props>> = function (props) {
  const userinfo = useSelector((state: any) => state.user.userinfo);
  const location = useLocation();
  if (!Object.keys(userinfo).length) {
    if (props.intoPermission) {
      if (location.pathname !== "/login" && location.pathname !== "/register") {
        return <Navigate to="/login" />;
      }
    }
  } else {
    if (location.pathname == "/login" || location.pathname == "/register") {
      return <Navigate to={"/home"}></Navigate>;
    }
  }
  /* 这里校验权限如果 intoPermission 为true code能找得到 再去校验权限，权限没通过的话跳转登录，如果code没有的话跳转404 */
  return props.children;
};
export default memo(Permission);
